package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    // 生成菜单树结构
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2.组装成分子的树形结构
        // 1.找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(item -> item.getParentCid() == 0).map(item -> {
            item.setChildren(getChildrens(item, entities));
            return item;
        }).sorted((menu1,menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        // 2.


        return level1Menus;
    }

    // 根据 id 删除分类
    @Override
    public void removeMenuByIds(List<Long> list) {
        // TODO 检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(list);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
//    @CacheEvict(value = "category", key = "'getLevel1Categorys'")
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = {"category"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName")
    public Map<String, List<Catalog2VO>> getCatalogJson(){
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1.查出所有1级类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

        // 2.封装数据
        Map<String, List<Catalog2VO>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1.每一个一级分类 查到该分类的2级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
            // 2.封装上面的结果
            List<Catalog2VO> catalog2Vos = null;

            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1. 找当前二级分类的三级分类 封装成vo
                    List<CategoryEntity> level3Catelog = getParentCid(selectList,l2.getCatId());
                    if (level3Catelog != null){
                        List<Catalog2VO.Catalog3Vo> catalog3Vos = level3Catelog.stream().map(l3 -> {
                            // 封装成指定的格式
                            Catalog2VO.Catalog3Vo catalog3Vo = new Catalog2VO.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(catalog3Vos);

                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }

            return catalog2Vos;
        }));
        return parentCid;
    }

    //TODO 产生堆外内存溢出：OutOfDirectMemoryError
    // 1. springboot2.0之后默认使用的是 lettuce 作为操作 redis 的客户端。它使用 netty 进行网络通信
    // 2. lettuce 的 bug 导致 netty 堆外内存溢出 默认使用 -Xmx100m
    //      可以通过 -Dio.netty.maxDirectMomery 进行设置
    // 解决方案：不能使用 -Dio.netty.maxDirectMomery 去调大内存
    // 1） 升级 lettuce 客户端    2）切换使用jedis
//    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson2(){
        /**
         * 1.空结果缓存：解决缓存穿透
         * 2.设置过期时间（加随机值）：解决缓存雪崩
         * 3.加锁：解决缓存击穿
         */
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)) {
            // 缓存中没有，查询数据库
            Map<String, List<Catalog2VO>> catalogJsonFromDb = getCatalogJsonFromDb();

            // 将对象转为 json
            String s = JSON.toJSONString(catalogJsonFromDb);

            // 放入缓存
            redisTemplate.opsForValue().set("catalogJson", s, 1, TimeUnit.DAYS);

            return catalogJsonFromDb;
        }

//        转为对象
        Map<String, List<Catalog2VO>> stringListMap = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2VO>>>() {});

        return stringListMap;
    }

//    从数据库查询数据
//    @Override
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDb() {

        /**
         * 1.将数据库多次查询变为1次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);


        // 1.查出所有1级类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

        // 2.封装数据
        Map<String, List<Catalog2VO>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 1.每一个一级分类 查到该分类的2级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
            // 2.封装上面的结果
            List<Catalog2VO> catalog2Vos = null;

            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 1. 找当前二级分类的三级分类 封装成vo
                    List<CategoryEntity> level3Catelog = getParentCid(selectList,l2.getCatId());
                    if (level3Catelog != null){
                        List<Catalog2VO.Catalog3Vo> catalog3Vos = level3Catelog.stream().map(l3 -> {
                            // 封装成指定的格式
                            Catalog2VO.Catalog3Vo catalog3Vo = new Catalog2VO.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(catalog3Vos);

                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }

            return catalog2Vos;
        }));
        return parentCid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
        // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths){
        // 收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(), paths);
        }

        return paths;

    }

    // 递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(item -> item.getParentCid().equals(root.getCatId())).map(item ->{
            // 1.找到子菜单
            item.setChildren(getChildrens(item, all));
            return item;
        }).sorted((menu1, menu2) -> {
            // 2. 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;

    }

}